package com.jp.forkjoin;

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class ForkJoinRecursiveTask {
    private static final  int MAX = 3;


    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> future = forkJoinPool.submit(new CalculateTask(1, 10));
        try {
            int result  = future.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    private static class CalculateTask extends RecursiveTask<Integer>{

        private int start;
        private int end;

        private CalculateTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            if(end-start <= MAX){
//                try {
//                    //TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                int sum=IntStream.rangeClosed(start,end).sum();
                System.out.printf("Thread[%s],sum=[%d-%d]\n",Thread.currentThread().getName(),start,end);
                return sum;
            }else{

                int mid= (end+start)/2;
                System.out.printf("Thread[%s],range=[%d-%d]\n",Thread.currentThread().getName(),start,end);
                CalculateTask t1 = new CalculateTask(start,mid);
                CalculateTask t2 = new CalculateTask(mid+1,end);
                t1.fork();
                t2.fork();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return t1.join()+t2.join();
            }
        }
    }
}
